import cv2
import numpy as np

# 读取图像
img = cv2.imread("Hull.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# 分别定义每个图形的HSV范围（需根据实际颜色微调）
# 红色菱形
lower_red = np.array([0, 50, 50])
upper_red = np.array([10, 255, 255])
mask_red = cv2.inRange(hsv, lower_red, upper_red)

# 黄色六边形
lower_yellow = np.array([20, 50, 50])
upper_yellow = np.array([30, 255, 255])
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)

# 紫色箭头
lower_purple = np.array([125, 43, 46])
upper_purple = np.array([155, 255, 255])
mask_purple = cv2.inRange(hsv, lower_purple, upper_purple)

# 绿色星形
lower_green = np.array([40, 50, 50])
upper_green = np.array([70, 255, 255])
mask_green = cv2.inRange(hsv, lower_green, upper_green)

# 紫色心形
lower_pink = np.array([140, 50, 50])
upper_pink = np.array([180, 255, 255])
mask_pink = cv2.inRange(hsv, lower_pink, upper_pink)

# 合并所有掩码
mask = cv2.bitwise_or(mask_red, mask_yellow)
mask = cv2.bitwise_or(mask, mask_purple)
mask = cv2.bitwise_or(mask, mask_green)
mask = cv2.bitwise_or(mask, mask_pink)

# 形态学操作优化掩码
kernel = np.ones((3, 3), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# 检测轮廓
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# 定义颜色列表
colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0), (255, 255, 0), (255, 0, 255)]

for i, cnt in enumerate(contours):
    if cv2.contourArea(cnt) < 100:
        continue
    hull = cv2.convexHull(cnt)
    cv2.drawContours(img, [hull], 0, colors[i % len(colors)], 4)

# 保存并显示结果
cv2.imwrite("convex_hull_all.png", img)
cv2.imshow("All Convex Hulls", img)
cv2.waitKey(0)
cv2.destroyAllWindows()